package com.jt.www.biz.order_pc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.layout.element.Image;
import com.jt.www.biz.order_pc.service.SxApplicationFormService;
import com.jt.www.dao.mapper.sxappform.SxApplicationFormMapper;
import com.jt.www.model.sxappform.SxApplicationFormInfo;
import com.jt.www.model.sxappform.SxApplicationFormParam;
import com.jt.www.model.sxappform.SxApplicationFormQo;
import com.jt.www.model.sxappform.SxApplicationFormVo;
import com.jt.www.util.DateUtils;
import com.jt.www.util.Html2PdfUtil;
import com.jt.www.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SxApplicationFormServiceImpl implements SxApplicationFormService {
    public static final Logger log = LoggerFactory.getLogger(SxApplicationFormServiceImpl.class);
    /**
     * 每日最大保存数
     */
    private static final int OUT_SIZE = 50000;
    @Autowired
    private SxApplicationFormMapper sxApplicationFormMapper;
    @Autowired
    private TemplateEngine templateEngine;

    @Override
    public Integer save(List<SxApplicationFormInfo> params) {
        //设置每日最大插入限制锁
        String key = "SAVE_APP_FORM_" + DateUtils.converDate(new Date());
        String value = RedisUtil.getValue(key);
        //判断之前有没有保存过
        if (StringUtils.isBlank(value)) {
            //没有保存过 设置初始值
            RedisUtil.setLock(key, "1", 1L, TimeUnit.DAYS);
        } else if (Integer.parseInt(value) > OUT_SIZE) {
            return 0;
        } else {
            RedisUtil.increment(key, 1);
        }

        int n = 0;
        for (SxApplicationFormInfo param : params) {
            param.setCreateTime(new Date());
            param.setIsDeleted(false);
            n += sxApplicationFormMapper.insertSelective(param);
        }

        return n;
    }


    @Override
    public PageInfo searchSxAppFormList(SxApplicationFormParam sxApplicationFormParam) {

        Page page = PageHelper.startPage(sxApplicationFormParam.getPn(), sxApplicationFormParam.getPs());
        List<SxApplicationFormVo> entities = sxApplicationFormMapper.searchSxAppFormList(sxApplicationFormParam);

        PageInfo info = new PageInfo(page);
        info.setList(entities);

        return info;
    }

    @Override
    public List<SxApplicationFormVo> downSxAppFormList(SxApplicationFormQo sxApplicationFormQo) {
        return sxApplicationFormMapper.downSxAppFormList(sxApplicationFormQo);
    }

    @Override
    public Integer updateSxAppStatus(Long id, String status) {
        SxApplicationFormInfo example = new SxApplicationFormInfo();
        example.setId(id);
        example.setStatus(status);
        return sxApplicationFormMapper.updateSxApplicationForm(example);
    }

    @Override
    public Integer updateSxAppValid(Long id, String isValid) {
        SxApplicationFormInfo example = new SxApplicationFormInfo();
        example.setId(id);
        example.setIsValid(isValid);
        return sxApplicationFormMapper.updateSxApplicationForm(example);
    }

    @Override
    public void downAppPdf(List<SxApplicationFormInfo> formInfos, HttpServletRequest request, HttpServletResponse response) {
        String findCode = "downAppPdf_" + System.currentTimeMillis();

        WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale());
        ctx.setVariable("appFormInfo", formInfos.get(0));
        String policyModel;
        float bottom1;
        float bottom2;
        String imgUrl;
        if (formInfos.size() > 1) {
            policyModel = "ins-xz-sx-jbw2";
            ctx.setVariable("appFormInfo2", formInfos.get(1));
            bottom1 = 230;
            bottom2 = 450;
            imgUrl = "img\\jt_seal.jpg";
        } else if ("山西省校园食品安全责任保险".equals(formInfos.get(0).getProductName())) {
            policyModel = "ins-sp-sx-jbw";
            bottom1 = 100;
            bottom2 = 320;
            imgUrl = "img\\sx_xd_seal.jpg";
        } else {
            policyModel = "ins-xz-sx-jbw";
            bottom1 = 100;
            bottom2 = 320;
            imgUrl = "img\\jt_seal.jpg";
        }

        String startDate = DateUtils.conver(DateUtils.str2Date(formInfos.get(0).getStartDate(), "yyyy-MM-dd"), "yyyy年MM月dd日");
        String endDate = DateUtils.conver(DateUtils.str2Date(formInfos.get(0).getEndDate(), "yyyy-MM-dd"), "yyyy年MM月dd日");
        ctx.setVariable("startDate", startDate);
        ctx.setVariable("endDate", endDate);

        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        ctx.setVariable("year", year);
        ctx.setVariable("month", month);
        ctx.setVariable("day", day);


        String templatespath = "/templates/" + policyModel + ".html";
        ServletOutputStream outputStream = null;
        InputStream is = null;
        try {
            // 返回读取指定资源的输入流
            is = this.getClass().getResourceAsStream(templatespath);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String s;
            StringBuffer sb = new StringBuffer();
            while ((s = br.readLine()) != null) {
                sb.append(s).append("\n");
            }
            String htmlcontext = templateEngine.process(policyModel, ctx);
            //添加盖章
            Resource resource = new ClassPathResource(imgUrl);
            Image indexImage = new Image(ImageDataFactory.create(resource.getURL()));
            indexImage.setMargins(-70, 70, 0, 0);
            indexImage.setHeight(100);
            indexImage.setWidth(100);
            indexImage.scaleToFit(50, 50);
            indexImage.setFixedPosition(450, bottom1);

            Image indexImage2 = new Image(ImageDataFactory.create(resource.getURL()));
            indexImage2.setMargins(-70, 70, 0, 0);
            indexImage2.setHeight(100);
            indexImage2.setWidth(100);
            indexImage2.scaleToFit(50, 50);
            indexImage2.setFixedPosition(450, bottom2);
            List<Image> images = Lists.newArrayList(indexImage, indexImage2);


            String path = "投保单_" + formInfos.get(0).getHolderName() + ".pdf";
            response.addHeader("Content-Disposition",
                    "attachment;fileName=" + URLEncoder.encode(path, "UTF-8"));
            response.setHeader("Content-Type", "application/pdf");
            outputStream = response.getOutputStream();
            outputStream.write(Html2PdfUtil.html2Pdf(htmlcontext, images));

            log.debug("{} 下载投保单生成PDF完成", findCode);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("{} 下载投保单PDF异常 {}", findCode, e);
        } finally {
            try {
                outputStream.close();
            } catch (Exception e) {
            }
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
}
